package com.superbit.service.userasset.service.dao;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.superbit.core.entry.User_Asset;
import com.superbit.utils.dbutil.CommonDao;

@Repository
public class User_AssetDao {
	private static Logger logger = LoggerFactory.getLogger(User_AssetDao.class);
	@Autowired
	private CommonDao commonDao;
	/**
	 * 返回用户资产记录数
	 * flag为0时获取全部币种
	 * flag为1时获取资产大于0的币种
	 * @param userId
	 * @param flag
	 * @return
	 */
	public int getUser_AssetTotalCount(int userId, int flag) {
		// TODO Auto-generated method stub
		logger.info("userId:"+userId+",flag:"+flag);
		List<Criterion> conds = new ArrayList<Criterion>();
		conds.add(Restrictions.eq("userId", userId));
		if(flag==1) {
			conds.add(Restrictions.gt("coinAmount", new BigDecimal("0")));
		}
		return commonDao.getCount(User_Asset.class, conds.toArray(new Criterion[0]));
	}
	/**
	 * 获取用户资产信息
	 * @param userId
	 * @param flag
	 * @param start
	 * @param end
	 * @return
	 */
	public List<User_Asset> getUser_AssetList(int userId, int flag, int start, int end) {
		// TODO Auto-generated method stub
		logger.info("userId:"+userId+",flag:"+flag+",start:"+start+",end:"+end);
		List<Criterion> conds = new ArrayList<Criterion>();
		conds.add(Restrictions.eq("userId", userId));
		if(flag==1) {
			conds.add(Restrictions.gt("coinAmount", new BigDecimal("0")));
		}
		Order[] orders = new Order[]{Order.desc("coinFreezeDate")};
		if(start<0) {
			return commonDao.getEntrysByCond(User_Asset.class, conds.toArray(new Criterion[0]), orders);
		}
		return commonDao.getEntrysByCond(User_Asset.class, conds.toArray(new Criterion[0]), orders, start, end);
	}
	
	/**
	 * 获取指定用户特定币种资产信息
	 * @param userId
	 * @param assetId
	 * @param coinId
	 * @return
	 */
	public User_Asset getUser_Asset(int userId, String coinId, String coinCode) {
		// TODO Auto-generated method stub
		logger.info("userId:"+userId+",coinId:"+coinId+",coinCode:"+coinCode);
		
		Criterion[] criteria = coinId!=null?new Criterion[]
				{Restrictions.eq("userId", userId), Restrictions.eq("coinId", coinId)}:new Criterion[]
								{Restrictions.eq("userId", userId), Restrictions.eq("coinCode", coinCode)};
		
		
		Order[] orders = new Order[]{Order.desc("coinAmount")};
		List<User_Asset> list = commonDao.getEntrysByCond(User_Asset.class, criteria, orders);
		if(list==null||list.size()==0){
			return null;
		}else{
			return list.get(0);
		}
	}
	
	
	/**
	 * 获取指定用户特定币种资产信息
	 * @param userId
	 * @param assetId
	 * @param coinId
	 * @param coinCode
	 * @return
	 */
	public User_Asset getUser_Asset(int userId, String assetId, String coinId, String coinCode) {
		// TODO Auto-generated method stub
		logger.info("userId:"+userId+",coinId:"+coinId+",coinCode:"+coinCode);
		
		Criterion[] criteria = assetId!=null?new Criterion[]
				{Restrictions.eq("userId", userId), Restrictions.eq("assetId", assetId)}:coinId!=null?new Criterion[]
								{Restrictions.eq("userId", userId), Restrictions.eq("coinId", coinId)}:
									new Criterion[]
											{Restrictions.eq("userId", userId), Restrictions.eq("coinCode", coinCode)};
		
		
		Order[] orders = new Order[]{Order.desc("coinAmount")};
		List<User_Asset> list = commonDao.getEntrysByCond(User_Asset.class, criteria, orders);
		if(list==null||list.size()==0){
			return null;
		}else{
			return list.get(0);
		}
	}
	/**
	 * 新增用户资产
	 * @param ua
	 * @return
	 */
	public boolean addUser_Asset(User_Asset ua) {
		int result = Integer.valueOf(commonDao.saveEntry(ua).toString());
		if(result>0) {
			return true;
		}else {
			return false;
		}
	}
	/**
	 * 修改用户资产等信息
	 * @param map
	 * @param id
	 * @return
	 */
	public boolean updateUser_Asset(Map<String, Object> map, int id) {
		// TODO Auto-generated method stub
		try {
			commonDao.updateEntry(User_Asset.class, map, id);
			return true;
		}catch(Exception e){
			logger.error(e.toString());
			return false;	
		}
	}
	/**
	 * 修改用户资产
	 * @param ua
	 * @return
	 */
	public boolean updateUser_Asset(User_Asset ua) {
		try {
			commonDao.updateEntry(ua);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	/**
	 *  冻结用户某种币种金额，或修改用户的固定资产
	 * @param flag 0 资产冻结/解冻，1充值
	 * @param amount  正数为充值或冻结，负值为解冻
	 * @return
	 * @throws UserAssetException 
	 */
	public boolean updateUser_Asset_Amount(User_Asset ua, int flag, BigDecimal amount) {
		// TODO Auto-generated method stub
		boolean result = false;
		if(flag==0) {// 冻结或解冻资产
//			ua.getCoinFreeze()
			if(amount.compareTo(new BigDecimal("0"))>0) {
				//冻结操作，比较剩余资产与将要冻结资产 >=
				if(ua.getCoinBalance().compareTo(amount)<0) {	
//					throw new BusinessException("WD202","剩余资产余额不足",""); 
					return false;
				}
			}else {
				//解冻操作，比较冻结资产与解冻资产   >=
				if(ua.getCoinFreeze().compareTo(amount)<0) {
//					throw new UserAssetException(ua.getUserId(), "WD203"); 
					return false;
				}
			}
			//修改剩余资产以及冻结资产，总资产不变
			ua.setCoinBalance(ua.getCoinBalance().subtract(amount));
			ua.setCoinFreeze(ua.getCoinFreeze().add(amount));
			
		}else if(flag==1) {// 资产充值
			//增加总资产以及剩余资产
			ua.setCoinAmount(ua.getCoinAmount().add(amount));
			ua.setCoinBalance(ua.getCoinBalance().add(amount));
		}else {
			return false;
		}
		try {
			commonDao.updateEntry(ua);
			result = true;
		}catch(Exception e) {
			logger.error(e.toString());
		}
		return result;
	}
	
	/**
	 * 返回用户总资产，以及对应人民币价格
	 * @param userId
	 * @return 
	 */
	public Map<String, User_Asset> getUser_Asset(int userId) {
		// TODO Auto-generated method stub
		Criterion[] criteria = new Criterion[]
				{Restrictions.eq("userId", userId)};
		Order[] orders = new Order[]{Order.desc("coinAmount")};
		List<User_Asset> list = commonDao.getEntrysByCond(User_Asset.class, criteria, orders);
		Map<String, User_Asset> map = new HashMap<String, User_Asset>();
		for(User_Asset ua:list) {
			map.put(ua.getCoinCode(), ua);
		}
		return map;
	}
	/**
	 * 根据用户Id和币种码获取对应的余额数
	 * @param userId 用户id
	 * @param coinCode 币种码
	 * @return
	 */
	public BigDecimal getCoinAmouts(int userId, String coinCode) {
		// TODO Auto-generated method stub
		Criterion[] criteria = new Criterion[]
				{Restrictions.eq("userId", userId), Restrictions.eq("coinCode", coinCode)};
		
		
		Order[] orders = new Order[]{Order.desc("coinAmount")};
		List<User_Asset> list = commonDao.getEntrysByCond(User_Asset.class, criteria, orders);
		if(list==null||list.size()==0){
			return null;
		}else{
			return list.get(0).getCoinBalance();
		}
	}
}
